package com.amc.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.amc.dao.ICommentDao;
import com.amc.dto.CommentView;
import com.amc.entity.Comment;
import com.amc.entity.Customer;
import com.amc.entity.Merchant;
import com.amc.entity.Order;

@Repository 
public class CommentDaoImpl implements ICommentDao {

	@PersistenceContext
	private EntityManager em;

	public void setEm(EntityManager em) {
		this.em = em;
	}

	@Override
	public boolean uploadComment(CommentView comment) {
		boolean result = false;
		Comment com = new Comment();
		System.out.println(em);
		try {
			com.setCommentTime(new Date());
			com.setCommentScore(comment.getCommentScore());
			com.setCommentText(comment.getCommentText());
			com.setCustomer(em.find(Customer.class, comment.getCustomerId()));
			com.setMerchant(em.find(Merchant.class, comment.getMerchantId()));
			com.setOrder(em.find(Order.class, comment.getOrderId()));
			em.persist(com);
			result = true;
		} catch (Exception e) {
			System.out.println("用户评论失败");
		}
		return result;
	}

	@Override
	public boolean replyComment(String commentId, String replyText) {
		boolean result = false;
		try {
			Comment com = em.find(Comment.class, commentId);
			com.setReplyText(replyText);
			com.setReplyTime(new Date());
			result = true;
		} catch (Exception e) {
			System.out.println("商家回复失败");
		}
		return result;
	}

	@Override
	public List<CommentView> showComment(String merchantId) {
		List<CommentView> commentViews = new ArrayList<>();
		Query query = em
				.createQuery(
						"select c from Comment c join fetch c.customer "
								+ "where c.merchant in (select m from Merchant m where m.merchantId=?)")
				.setParameter(1, merchantId);
		try {
			List<Comment> comments=query.getResultList();
			for(Comment c:comments)
			{
				commentViews.add(new CommentView(c.getCommentId(), c.getOrder().getOrderId(), c.getCommentText(), c.getReplyText(), c.getMerchant().getMerchantId(), c.getCustomer().getCustomerId(),c.getCustomer().getCustomerName(), c.getCommentScore(), c.getCommentTime(), c.getReplyTime()));
			}
		} catch (Exception e) {
			System.out.println("评论显示错误");
		}
		return commentViews;
	}

}
